from base import errors
from base import controllers as base_ctl
from account.models import UserModel
from account.models import MessageModel


def create_message(name, typ, content):
    '''
    创建消息
    '''
    user_obj = UserModel.objects.filter(name=name).first()
    if not user_obj:
        return
    if not MessageModel.check_choices('typ', typ):
        return
    data = {
        'user_id': user_obj.id,
        'typ': typ,
        'content': content,
    }
    base_ctl.create_obj(MessageModel, data)


def get_messages(zone=None, master_id=None, name=None, typ=None, page_num=None, page_size=None):
    '''
    获取消息列表
    '''
    base_query = MessageModel.objects
    if typ:
        base_query = base_query.filter(typ=typ)
    if name:
        base_query = base_query.filter(user__name__icontains=name)
    if zone:
        base_query = base_query.filter(user__zone=zone)
    if master_id:
        base_query = base_query.filter(user__master_id__icontains=master_id)
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        data['user'] = obj.user.to_dict()
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data
